<template>
  <RenderTableColumn v-bind="column" />
</template>
<script setup lang="tsx" name="TableCol">
import { getProp, handleRowAccordingToProp, filterEnum, formatValue, filterEnumLabel } from '@/utils'
defineProps<{ column: EcoTable.Column }>()
const slots = useSlots()
const enumMap = inject('enumMap', ref(new Map()))
// 渲染表格数据
const renderCellData = (item: EcoTable.Column, scope: TableRenderScope<any>, enumData: any) => {
  return unref(enumMap).get(item.prop!) && item.isFilterEnum
    ? filterEnumLabel(enumData, item.fieldNames)
    : formatValue(handleRowAccordingToProp(scope.row, item.prop!))
}
const getEnumData = (item: EcoTable.Column, scope: TableRenderScope<any>) => {
  return unref(enumMap).get(item.prop!) && item.isFilterEnum
    ? filterEnum(handleRowAccordingToProp(scope.row, item.prop!), unref(enumMap).get(item.prop!), item.fieldNames)
    : ''
}

// 获取 tag 类型
const renderTag = (item: any, data: any, last = true, index?: number) => {
  const { tagType, tagEffect } = item
  if (['el-check-tag', 'ElCheckTag'].includes(item.eTag)) {
    return (
      <>
        <el-check-tag key={index} checked type={tagType || 'primary'}>
          {data}
        </el-check-tag>
        {last ? '' : ' '}
      </>
    )
  }
  return (
    <>
      <el-tag key={index} type={tagType} effect={tagEffect || 'light'}>
        {data}
      </el-tag>
      {last ? '' : ' '}
    </>
  )
}
const RenderTableColumn = (item: EcoTable.Column) => {
  return (
    <>
      {item.isShow && (
        <el-table-column {...item} align={item.align ?? 'center'} showOverflowTooltip={item.showOverflowTooltip ?? item.prop !== 'operation'}>
          {{
            default: (scope: TableRenderScope<any>) => {
              if (item._children) return item._children.map(child => RenderTableColumn(child))
              if (item.render) return item.render(scope)
              if (item.prop && slots[getProp(item.prop)]) return slots[getProp(item.prop)]!(scope)
              const enumData = getEnumData(item, scope)
              const data = renderCellData(item, scope, enumData)
              if (item.tag && enumData) {
                if (Array.isArray(enumData)) {
                  return enumData.map((e, index) => renderTag(e, data[index], enumData.length - 1 === index, index))
                }
                return renderTag(enumData, data)
              }
              return Array.isArray(data) ? data.join(',') : data
            },
            header: (scope: HeaderRenderScope<any>) => {
              if (item.headerRender) return item.headerRender(scope)
              if (item.prop && slots[`${getProp(item.prop)}Header`]) return slots[`${getProp(item.prop)}Header`]!(scope)
              return item.label
            }
          }}
        </el-table-column>
      )}
    </>
  )
}
</script>
